#!/bin/bash

# Kubernetes MCP 服务器启动脚本

# 脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

# 设置颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查前置条件
check_prerequisites() {
    log_info "检查前置条件..."
    
    # 检查 Go
    if ! command -v go &> /dev/null; then
        log_error "Go 未安装或不在 PATH 中"
        exit 1
    fi
    log_success "Go 已安装: $(go version)"
    
    # 检查 kubectl
    if ! command -v kubectl &> /dev/null; then
        log_error "kubectl 未安装或不在 PATH 中"
        exit 1
    fi
    log_success "kubectl 已安装"
}

# 构建应用
build_app() {
    log_info "构建 K8s MCP 服务器..."
    
    cd "$PROJECT_ROOT/src" || exit 1
    
    # 下载依赖
    log_info "下载 Go 依赖..."
    if ! go mod tidy; then
        log_error "下载依赖失败"
        exit 1
    fi
    
    # 编译
    log_info "编译应用程序..."
    mkdir -p "$PROJECT_ROOT/bin"
    if go build -o "$PROJECT_ROOT/bin/k8s-mcp-server" .; then
        log_success "编译成功: $PROJECT_ROOT/bin/k8s-mcp-server"
    else
        log_error "编译失败"
        exit 1
    fi
    
    cd - > /dev/null
}

# 启动服务器
start_server() {
    local binary="$PROJECT_ROOT/bin/k8s-mcp-server"
    
    if [ ! -f "$binary" ]; then
        log_error "可执行文件不存在: $binary"
        log_info "正在构建应用..."
        build_app
    fi
    
    log_info "启动 K8s MCP 服务器..."
    log_success "K8s MCP 服务器启动中..."
    echo "----------------------------------------"
    
    # 切换到项目根目录，确保相对路径正确
    cd "$PROJECT_ROOT" || exit 1
    
    # 启动服务器
    exec "$binary"
}

# 主函数
main() {
    check_prerequisites
    build_app
    start_server
}

# 运行主函数
main "$@" 